//
//  NetworkIndicatorPlugin.swift
//  XNetwork_Example
//
//  Created by x on 2024/8/9.
//  Copyright © 2024 CocoaPods. All rights reserved.
//

import Moya

public final class NetworkIndicatorPlugin: PluginType {
    
    private static var numberOfRequests: Int = 0 {
        didSet {
            if numberOfRequests > 1 { return }
            guard #available(iOS 13.0, *) else {
                DispatchQueue.main.async {
                    UIApplication.shared.isNetworkActivityIndicatorVisible = self.numberOfRequests > 1
                }
                return
            }
        }
    }
    
    public init() {}
    
    public func willSend(_ request: any RequestType, target: any TargetType) {
        NetworkIndicatorPlugin.numberOfRequests += 1
    }
    
    public func didReceive(_ result: Result<Response, MoyaError>, target: any TargetType) {
        NetworkIndicatorPlugin.numberOfRequests -= 1
    }
}
